#!coding=utf-8
'''
Created on 2014-10-28
@author: Administrator
'''
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.http.response import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from zto.models import PackageInfo, StoreInfo,CustPostAdr, CustPostInfo,\
    postadmin, Town, Suggest, News, Transfee, Advantage
import base64
import hashlib
from zto import settings
import json
import requests
from weixin.api.common import getWebAccToken, calcDistance, sedTempMsg
from django.core import serializers
import datetime
from weixin.models import User


def index(request):
    template='index.html'
    return render_to_response(template,context_instance=RequestContext(request))

def wuliuinfo(request):
    p1 = request.GET.get('wldh')
    p2 = request.GET.get('openid')
    wuliuinfo=getBillInfo(p1);
    if wuliuinfo!=0:
        pro_step=0;
        pro_name="";
        if(u"签收" in wuliuinfo):
            pro_name="sign";
            pro_step=3;
        elif(u"派件" in wuliuinfo):
            pro_name="delivery";
            pro_step=2;
        elif(u"到达" in wuliuinfo):
            pro_name="transport";
            pro_step=1;
        else:
            pro_name="pick-up";
            pro_step=0;
#             
        try:
            p=PackageInfo.objects.get(pg_id=p1,wx_id=p2)  # @UndefinedVariable
            p.pg_step=pro_step;
            p.pg_sts=pro_name;
            p.save();
        except ObjectDoesNotExist:
            params={'errormsg':'error'}
            return render_to_response("query.html",params,context_instance=RequestContext(request))
        template='wuliuinfo.html';
        params={'wldh':p1,'wuliuinfo':wuliuinfo,'pro_name':pro_name,'pro_step':pro_step}
        return render_to_response(template,params,context_instance=RequestContext(request))
    else:
        params={'errormsg':'error'}
        return render_to_response("query.html",params,context_instance=RequestContext(request))

def query(request):
    template='query.html'
    return render_to_response(template,context_instance=RequestContext(request))

def ditupath(request):
    template='ditupath.html'
    return render_to_response(template,context_instance=RequestContext(request))

def getstoreinfo(request):
    p1 = request.GET.get('LX')
    p2 = request.GET.get('LY')
    list=getStroe(p1,p2)
    return HttpResponse(list)

def getdata(request):
    
    p1 = request.GET.get('code')
    p2 = request.GET.get('wldh')
    openid=request.session.get('openid',False)
    if openid == False:
        print "put session"
        openid=getWebAccToken(p1)
        request.session['openid']=openid
    
    try:
        PackageInfo.objects.get(pg_id=p2,wx_id=openid)  # @UndefinedVariable
    except ObjectDoesNotExist:
        pginfo=PackageInfo(pg_id=p2,wx_id=openid);
        pginfo.save();
        
    return HttpResponse(openid);

def storeinfo(request):
    return render_to_response("storeinfo.html",context_instance=RequestContext(request))


def addadress(request):
    return render_to_response("addadress.html",context_instance=RequestContext(request))

def addadr(request):
    ContactName=request.POST.get('ContactName')
    Mobile=request.POST.get('Mobile')
    Sender=request.POST.get('Sender')
    Address=request.POST.get('Address')
    openid=request.POST.get('openid')
    try:
        CustPostAdr.objects.get(wx_id=openid,phoneno=Mobile,detailAdrinfo=Address)  # @UndefinedVariable
    except ObjectDoesNotExist:
        pginfo=CustPostAdr(wx_id=openid,custname=ContactName,phoneno=Mobile,cityname=Sender,detailAdrinfo=Address);
        pginfo.save();
    
    return HttpResponse("true")

def getadress(request):
    
    openid=request.GET.get('openid')
    adrlist=CustPostAdr.objects.filter(wx_id=openid);
    params={'adrlist':adrlist,'openid':openid}
    return render_to_response("manadr.html",params,context_instance=RequestContext(request))

def postorder(request):
    return render_to_response("postorder.html",context_instance=RequestContext(request))

def orderview(request):
    return render_to_response("orderview.html",context_instance=RequestContext(request))

def orderinfo(request):
#     topenid=request.session.get('openid',False)
    torderid = request.GET.get('orderid')
    tmporder=None;
    try:
        tmporder=CustPostInfo.objects.get(orderid=torderid);  # @UndefinedVariable
    except ObjectDoesNotExist:
        return HttpResponse("订单已被取消")
    params={'tmporder':tmporder}
    return render_to_response("orderinfo.html",params,context_instance=RequestContext(request))

def ordercancel(request):
    id = request.POST.get('id')
    topenid=request.session.get('openid',False)
#     ckReason = request.POST.get('ckReason')
    try:
        tmporder=CustPostInfo.objects.get(id=int(id),wx_id=topenid);  # @UndefinedVariable
        tmporder.delete();
    except ObjectDoesNotExist:
        return HttpResponse("error")
    
    return HttpResponse("true")

def getorderfee(request):
#     Sender = request.POST.get('Sender')
    JSender = request.POST.get('JSender')
    Weight = request.POST.get('Weight')
    code = request.POST.get('code')
    topenid=request.session.get('openid',False)
    if topenid == False:
        topenid=getWebAccToken(code)
        request.session['openid']=topenid
    fee=0
#     str='江苏省-苏州市-昆山市'
    prov=JSender[0:JSender.index('-')][0:2]
    queryset=Transfee.objects.filter(province__startswith=prov)
    
    for tmpset in queryset:
        if Weight == "1" :
            try:
                user=User.objects.get(openid=topenid);
                if user.post_times=="":
                    fee=(float(tmpset.first_weight_fee))*0.8
                    return HttpResponse(fee)
                else:
                    fee=(float(tmpset.first_weight_fee))*0.8
                    return HttpResponse(fee)
            except ObjectDoesNotExist:
                fee=(float(tmpset.first_weight_fee))*0.8
                return HttpResponse(fee)
        else:
            fee=(float(tmpset.first_weight_fee)+(float(Weight)-1)*float(tmpset.goon_weight_fee))*0.8
            return HttpResponse(fee)
    
    
def order(request):
    p1 = request.GET.get('code')
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(p1)
        request.session['openid']=openid
#     
    
    adrlist=CustPostAdr.objects.filter(wx_id=openid)  # @UndefinedVariable
    
    params={'adrlist':adrlist,'openid':openid}
        
    return render_to_response("order.html",params,context_instance=RequestContext(request))

def addorder(request):
    orderfee = request.POST.get('orderfee')
    ContactName = request.POST.get('ContactName')
    Mobile = request.POST.get('Mobile')
    Sender = request.POST.get('Sender')
    Address = request.POST.get('Address')
    JContactName = request.POST.get('JContactName')
    JMobile = request.POST.get('JMobile')
    JSender = request.POST.get('JSender')
    JAddress = request.POST.get('JAddress')
    Weight = request.POST.get('Weight')
    Category = request.POST.get('Category')
    Remark = request.POST.get('Remark')
    code = request.POST.get('code')
    Orderid= request.POST.get('orderid')
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(code)
        request.session['openid']=openid
    #新增用户的寄件地址信息
    try:
        CustPostAdr.objects.get(wx_id=openid,detailAdrinfo=Address,phoneno=Mobile,custname=ContactName);  # @UndefinedVariable
        
    except ObjectDoesNotExist:
        postAdr=CustPostAdr(wx_id=openid,custname=ContactName,phoneno=Mobile,cityname=Sender,detailAdrinfo=Address);
        postAdr.save()
        
    #防止页面订单金额为0的情况
    if orderfee=="0":
        prov=JSender[0:JSender.index('-')][0:2]
        queryset=Transfee.objects.filter(province__startswith=prov)
        for tmpset in queryset:
            if Weight == "1" :
                try:
                    user=User.objects.get(openid=openid);  # @UndefinedVariable
                    if user.post_times.strip()=="":
                        fee=(float(tmpset.first_weight_fee))*0.8
                        orderfee=fee;
                    else:
                        fee=(float(tmpset.first_weight_fee))*0.8
                        orderfee=fee;
                except ObjectDoesNotExist:
                    fee=(float(tmpset.first_weight_fee))*0.8
                    orderfee=fee;
            else:
                fee=(float(tmpset.first_weight_fee)+(float(Weight)-1)*float(tmpset.goon_weight_fee))*0.8
                orderfee=fee;
                  
    #更新用户寄件数量
    try:
        user=User.objects.get(openid=openid);  # @UndefinedVariable
        if user.post_times!="":
            tmptimes=int(user.post_times)+1
            user.post_times=tmptimes
            user.save()
        else:
            user.post_times='1'
            user.save()
    except ObjectDoesNotExist:
        postAdr=User(openid=openid,postpost_times_times='1');
        postAdr.save()
    
    #新增订单信息
    custorder=CustPostInfo(wx_id=openid,orderid=Orderid,P_custname=ContactName,P_phoneno=Mobile,P_cityname=Sender,P_detailAdrinfo=Address,
                                        g_custname=JContactName,g_phoneno=JMobile,g_cityname=JSender,g_detailAdrinfo=JAddress,
                                        postfee=orderfee,weight=Weight,things=Category,content=Remark);
    custorder.save();        
    
    sendordermsgtocust(openid,Orderid);
    sendordermsgtoadmin(Orderid);
    return HttpResponse("true")

def deladr(request):
    
    idno=request.POST.get('id')
    
    try:
        tmpadr=CustPostAdr.objects.get(id=int(idno));  # @UndefinedVariable
        
        tmpadr.delete();
    except ObjectDoesNotExist:
        return HttpResponse("error")
    
    return HttpResponse("true")
    
def townlist(request):
    townlist=Town.objects.all()
    
    params={'townlist':townlist}
    return render_to_response("townlist.html",params,context_instance=RequestContext(request))

def siteinfo(request):
    siteid=request.GET.get('siteid')
    tmpsite=StoreInfo.objects.get(id=int(siteid));
    params={'tmpsite':tmpsite}
    return render_to_response("siteinfo.html",params,context_instance=RequestContext(request))

def suggestadd(request):
    code=request.POST.get('code')
    Tname=request.POST.get('Name')
    Tphone=request.POST.get('Mobile')
    Tadress=request.POST.get('Address')
    suggest=request.POST.get('SugContent')
    
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(code)
        request.session['openid']=openid
        
    try:
        Suggest.objects.get(wx_id=openid,sugcont=suggest)  # @UndefinedVariable
    except ObjectDoesNotExist:
        pginfo=Suggest(wx_id=openid,name=Tname,phone=Tphone,sugcont=suggest,adress=Tadress);
        pginfo.save();
    
    return HttpResponse("true")
    
def news(request):
    news=News.objects.all().order_by('-modified'); #-表示降序排
    params={'news':news}
    return render_to_response("news.html",params,context_instance=RequestContext(request))

def advantage(request):
    
    advant=Advantage.objects.all()[0];
    params={'advant':advant}
    return render_to_response("advantage.html",params,context_instance=RequestContext(request))

def newcont(request):
    
    newid=request.GET.get('id')
    tmpnew=News.objects.get(id=int(newid));
    params={'tmpnew':tmpnew}
    return render_to_response("newcont.html",params,context_instance=RequestContext(request))

def suggest(request):
    openid=request.GET.get("openid")
    try:
        user=User.objects.get(openid=openid);
    except ObjectDoesNotExist:
        user=User(openid=openid)
        user.save();
    params={'user':user}
    return render_to_response("suggest.html",params,context_instance=RequestContext(request))

def regadmin(request):
    
    return render_to_response("regadmin.html",context_instance=RequestContext(request))

def addadmin(request):
    
    code=request.POST.get('code')
    Tname=request.POST.get('Name')
    Tphone=request.POST.get('Mobile')
    Tcertid=request.POST.get('certid')
    
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(code)
        request.session['openid']=openid
        
    try:
        postadmin.objects.get(wx_id=openid)  # @UndefinedVariable
    except ObjectDoesNotExist:
        pginfo=postadmin(wx_id=openid,name=Tname,phone=Tphone,certid=Tcertid);
        pginfo.save();
        return HttpResponse("true")
    
    return HttpResponse("error")
        
def sitelist(request):
    townid=request.GET.get("townid")
    
    sitelist=StoreInfo.objects.filter(town=townid)
    if sitelist:
        params={'sitelist':sitelist}
        return render_to_response("sitelist.html",params,context_instance=RequestContext(request))
    else:
        return HttpResponse("暂无网点信息");
    
def feelist(request):
    feelist=Transfee.objects.all()
    print feelist
    params={'feelist':feelist}
    return render_to_response("feelist.html",params,context_instance=RequestContext(request))
    
def getBillInfo(billno):
    respdata=[];
    data="['%s']" % billno;
    data_digest=base64.encodestring((hashlib.md5(u"%s%s"%(data,settings.key)).digest())).strip('\n')  # @UndefinedVariable
    url="http://japi.zto.cn/zto/api_utf8/traceInterface?data=['{0}']&data_digest={1}&msg_type=NEW_TRACES&company_id=0b60240597ea4d76916ed6287a4fabae&billCodes={2}".format(billno,data_digest,billno);
    
    try:
        data=requests.get(url);
        res=json.loads(data.content);
        resdata=res['data'][0];
        for i in resdata:
            if i == 'traces':
                for j in range(len(resdata[i])):
                    strtmp= resdata[i][j]['scanDate']+"+";
                    
                    if (u'收件' in resdata[i][j]['desc'] or u'到达' in resdata[i][j]['desc'] or u'派件' in resdata[i][j]['desc'] or u'签收' in resdata[i][j]['desc']):
                        strtmp+= resdata[i][j]['desc'];
                    else:
                        strtmp+= resdata[i][j]['desc']+"，目的地："+resdata[i][j]['preOrNextSite'];
                    respdata.append(strtmp+",");
        resstr=''.join(reversed(respdata));
        return resstr[0:len(resstr)-1];
    except :
        return 0;


def getStroe(Location_X,Location_Y):
    qset=StoreInfo.objects.all();
    
    liststroe=[]
    listdis=[]
    
    for tmpset in qset:
        if tmpset.latitude!="" and tmpset.longitude!="":
            dis=calcDistance(float(Location_X),float(Location_Y),float(tmpset.latitude),float(tmpset.longitude))
            if dis < 10000 :
                liststroe.append(tmpset)
                listdis.append(dis)
    
    if len(listdis)==0:
        return 0;
    else:
        data = serializers.serialize("json", liststroe)
        jsonlist = json.loads(data.encode('utf-8'))
        print json.dumps(jsonlist,ensure_ascii=False);
        return json.dumps(jsonlist,ensure_ascii=False);

#send msg to user
def sendordermsgtocust(openid,orderno):
    msg={
           "touser":openid,
           "template_id":"2yErPAr_J_ldZaCvZVEJfl8-RIRaxal43t4K7uUfywM",
           "url":"http://zto.wuxizto.com/orderinfo/?orderid="+orderno,            
           "data":{
                   "first":{
                        "value":"恭喜您，下单成功。即将为您服务的快递员信息如下：",
                        "color":"#173177"
                    },
                     "keyword1":{
                            "value":"贾",
                            "color":"#173177"
                        },
                       "keyword2":{
                            "value":"18762691641",
                            "color":"#173177"
                        },
                    "remark":{
                        "value":"谢谢关注中通物流",
                        "color":"#173177"
                    }  
            }
        }
    encodedjson=json.dumps(msg);
    sedTempMsg(encodedjson);
    
#send msg to admin
def sendordermsgtoadmin(orderno):
    adminlist=postadmin.objects.filter(adminsts='2');
    ordertime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for tmpset in adminlist:
        msg={
               "touser":tmpset.wx_id,
               "template_id":"2yErPAr_J_ldZaCvZVEJfl8-RIRaxal43t4K7uUfywM",
                "url":"http://zto.wuxizto.com/orderinfo/?orderid="+orderno,            
               "data":{
                       "first":{
                        "value":"有新订单创建，请迅速响应。",
                        "color":"#173177"
                    },
                        "keyword1":{
                            "value":"寄件订单",
                            "color":"#173177"
                        },
                       "keyword2":{
                            "value":orderno,
                            "color":"#173177"
                        },
                       "keyword3":{
                            "value":ordertime,
                            "color":"#173177"
                        },
                       "remark":{
                        "value":"谢谢关注",
                        "color":"#173177"
                    } 
                }
            }
        encodedjson=json.dumps(msg);
        sedTempMsg(encodedjson);
